<template>
  <div>
    <dv-border-box1>
      <div ref="chartRef" style="height: 290px; width: 100%; padding: 10px"></div>
    </dv-border-box1>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onBeforeUnmount } from 'vue'
  import * as echarts from 'echarts'

  const chartRef = ref<HTMLDivElement | null>(null)
  let chartInstance: echarts.ECharts | null = null
  //当前视口宽度
  let nowClientWidth = ref(document.documentElement.clientWidth)
  //换算方法
  function nowSize(val: number, initWidth = 1920) {
    return val * (nowClientWidth.value / initWidth)
  }

  const option = {
    // backgroundColor: '#fff',
    title: {
      text: '2500m当量钻井周期',
      left: 10,
      top: 10,
      textStyle: {
        color: '#000',
        fontSize: nowSize(18),
        fontWeight: 'bold',
      },
    },
    grid: {
      left: 30,
      right: 20,
      top: 50,
      bottom: 30,
    },
    xAxis: {
      type: 'category',
      data: ['2022', '2023', '2024', '2025'],
      axisLine: {
        lineStyle: {
          color: '#b3b3b3',
        },
      },
      axisLabel: {
        color: '#333',
        fontSize: nowSize(14),
      },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 15,
      interval: 3,
      axisLine: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          color: '#e0e0e0',
        },
      },
      axisLabel: {
        color: '#333',
        fontSize: nowSize(14),
      },
    },
    series: [
      {
        type: 'bar',
        data: [11.99, 11.86, 11.78, 10.53],
        barWidth: nowSize(48),
        itemStyle: {
          color: function (params: any) {
            const colors = ['#4bb6ff', '#4bb6ff', '#4bb6ff', '#1de9b6']
            return colors[params.dataIndex]
          },
          borderRadius: [8, 8, 0, 0],
        },
        label: {
          show: true,
          position: 'top',
          color: '#000',
          fontSize: nowSize(16),
          fontWeight: 'bold',
          formatter: function (params: any) {
            return params.value.toFixed(2)
          },
          // backgroundColor: function (params: any) {
          //   return params.dataIndex === 3 ? '#1de9b6' : '#4bb6ff'
          // },
          borderRadius: 6,
          padding: [2, 8],
        },
      },
    ],
  }

  onMounted(() => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
      chartInstance.setOption(option)
      window.addEventListener('resize', resizeChart)
    }
  })

  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.dispose()
    }
    window.removeEventListener('resize', resizeChart)
  })

  function resizeChart() {
    if (chartInstance) {
      nowClientWidth.value = document.documentElement.clientWidth
      chartInstance.setOption(option)
      chartInstance.resize()
    }
  }
</script>

<style scoped lang="scss"></style>
